package com.safe.first.infrastructure.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWTUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.safe.first.domain.user.DefaultUser;
import com.safe.first.infrastructure.model.JwtToken;
import com.safe.first.infrastructure.model.JwtTokenData;
import lombok.AllArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Mickey
 * @since 2022/6/14
 **/
@Service
@AllArgsConstructor
public class TokenService {

    private final ObjectMapper objectMapper;

    public JwtToken token(Authentication authentication) {
        DefaultUser defaultUser = (DefaultUser) authentication.getPrincipal();
        long currentTimeMillis = System.currentTimeMillis();
        long accessTokenExpire = currentTimeMillis + 1000 * 60 * 60 * 24 * 15;
        Map<String, Object> map = new HashMap<>() {
            private static final long serialVersionUID = 1L;

            {
                put("iat", currentTimeMillis);
//                try {
//                    put("data", objectMapper.writeValueAsString(new JwtTokenData(2313L, Arrays.asList("da", "dadd"))));
//                } catch (JsonProcessingException e) {
//                    throw new RuntimeException(e);
//                }
                put("uid", defaultUser.getId().toString());
                put("jti", IdUtil.nanoId());
                put("exp", accessTokenExpire);
            }
        };

        Map<String, Object> map2 = new HashMap<>() {
            private static final long serialVersionUID = 1L;

            {
                put("uid", defaultUser.getId());
                put("jti", IdUtil.nanoId());
                put("expire_time", System.currentTimeMillis() + 1000L * 600 * 60 * 24 * 15);
            }
        };

        String token = JWTUtil.createToken(map, "1234".getBytes());
        String token2 = JWTUtil.createToken(map2, "1234".getBytes());

        JwtToken jwtToken = new JwtToken();
        jwtToken.setAccessToken(token);
        jwtToken.setExpire(accessTokenExpire);
        jwtToken.setRefreshToken(token2);

        return jwtToken;
    }

}
